Client-side Scripting Languages Introduction to Javascript
Plan du course Javascript – Pourquoi?, Ou?, Qu-est ce que c’est? Comment ajouter Javascript au HTML La syntaxe du Javascript  Document Object Model Exemples
Javascript – Pourquoi?, Ou?, Qu-est ce que c’est? Au début – simple texte + images + liens Des pages “live” ont été nécessaires sur le web  Netscape a invente “LiveScript” en 1995 LiveScript a change le nom plus tard en Javascript Javascript – fonctionne sur des navigateurs, permet de l'accès dynamique à la page html  Le langage a été interprété dans un façon différent de navigateurs différents
Include Javascript into HTML Script inclus dans la page html  <script type=”text/javascript”> //code script </script> Script inclus dans un fichier extérieur <script src=”fisier_surse.js”></script>
Quand est le code exécuté Si le tag “script” est inclus dans le tag “head” Le script est exécuté lorsque la page est chargée - avant de rendre  Si le script est inclus dans le corps page  Le script est exécuté lorsque le balisage est
Syntaxe du Javascript Similaire avec C & Java Les variables n’ont pas du type Les variables sont déclaré en utilisant le mot “var”  var x=5, y=7; Les fonctions sont déclaré en utilisant le mot “function” function sum(x,y) { var rez=x+y; return rez;} Les fonctions sont appelées comme en C/Java var suma=sum(2,5);
Les objets du Javascript Les objets ont des methodes (fonctions) Proprietes Exemple var student={nom: &quot;ion&quot;, an:2, notes:{mate:9, pc:8}}; alert(student.nom +&quot;<br>&quot; ); alert(student.an +&quot;<br>&quot;);
References pour les objets du Javascript Math http://www.w3schools.com/jsref/jsref_obj_math.asp   String http://www.w3schools.com/jsref/jsref_obj_string.asp   Array http://www.w3schools.com/jsref/jsref_obj_array.asp   Date http://www.w3schools.com/jsref/jsref_obj_date.asp
Examples <script type=&quot;text/javascript&quot;> function printValue() //declare a function { var x=Math.random()*10; //compute the value of x as a random value between 0 and 10 alert(x); //display an alert containing the value of x var y=&quot;a random text&quot;; //create a variable of type string alert(y.length); //display an alert containing the length of y //!!! length is a property and not a method alert(y.substr(0,5)); //compute and display as an alert the substring of y between the first and the 5 th  character alert(x+&quot; &quot;+y.length+&quot; &quot;+y.substr(5,y.length)); //display as an alert the string formed by x, length of y and the substring formed from the 5 th  character of y until the last one } </script>
Javascript exemple - analyse “ +” est utilise pour aider les strings  “ alert” est utilise pour afficher d’information pendant le développement. Il ne doit pas etre utilise en applications Les objets peuvent avoir des méthodes comme y.substr(0,5) et propriétés comme y.length
Evénements Les éléments du HTML peuvent détecter quand l’utilisateur a des interactions avec eux Exemples d’interactions Mouse over (mouse out) Click Key pressed Blur change Nous pouvons écrire du code Javascript pour traiter les interactions
Events examples <script type=“text/javascript”> function youClicked(element) {element.innerHTML=&quot;you clicked this element&quot;;} function youMousedOver() {alert(&quot;mouse over detected&quot;); } </script> <h1 onclick=&quot;alert('youclicked');youClicked( this );&quot; onmouseover=&quot;youMousedOver()&quot;> Introduction dans la programmation web</h1>
Evénements Qu’est que c’est “this” Html element User interacts event1 event2 Event1 a une fonction javascript La fonction javascript doit savoir quel élément a modifier “ this” est la référence a l’objet qui doit être modifie
DOM DOM=Document Object Model DOM = une representation des elements de la page HTML
DOM The DOM tree contains nodes which can be Html elements Text  The tree elements can be accessed By traversing the tree (See Data structures course) By accessing them directly by name (getElementsByTagName) By accessing them directly by id (getElementById) Addressing them directly (as in an array) The root of the DOM tree is the document
Methods and properties document.write(“text”) Adds the “text” to the given page If the page is finished loading it rewrites it Example <script type=&quot;text/javascript&quot;> function printValue() { var x=Math.random()*10; alert(x); var y=&quot;a random text&quot;; alert(y.length); alert(y.substr(0,5)); alert(x+&quot; &quot;+y.length+&quot;!!!&quot;+y.substr(5,y.length)); document.write(x+&quot; &quot;+y.length+&quot;!!!&quot;+y.substr(5,y.length)); } </script>
DOM Methods and properties getElementsByTagName Returns an array of elements with a given name The we need to know the position of the element we need to modify inside the array function modifySecondH1() { var headersArray=document.getElementsByTagName(&quot;h1&quot;); //retrieves all the elements whose names are h1 //elements’ numbering in the array starts at 0 headersArray[1].innerHTML=Math.random()*5; }
DOM Methods and properties document.getElementById The most used method to access an element of a html page We have to be careful to set ids for the elements function modifyFirstH1() { //retrieve the element with the id h1id1 var h1Element=document.getElementById(&quot;h1id1&quot;); //set the HTML value for the document h1Element.innerHTML=&quot;new title&quot;; }
DOM objects methods and properties Direct access to the element Predefined collections Forms Links  Images document.forms[0].username.value – accesses the first form in the document and sets the value property for the username input
Example – using javascript to validate forms When a form is submitted we need to validate it first on the client-side The form should be validated before submitting The event should be added to the submit button For example we want to check if 2 passwords have the same value and if the username is longer than 4 characters
Validate forms with Javascript – example (I) function validateForm(){ var usernameElement=document.getElementById(&quot;username&quot;); var passwordElement=document.getElementById(&quot;password&quot;); var rePasswordElement=document.getElementById(&quot;repassword&quot;); if(passwordElement.value!=rePasswordElement.value || passwordElement.value.length==0) {alert(&quot;please make sure the password is entered the same twice&quot;);return;} if (usernameElement.value.length<4) {alert(&quot;please make sure the username is longer than 4 letters&quot;);return; } document.forms[0].submit(); }
Example of form validation with Javascript (II) <form action=&quot;script.php&quot; method=&quot;POST&quot;> nom d'utilisateur<input type=&quot;text&quot; id=&quot;username&quot; /><br/> mot de passe<input type=&quot;password&quot; id=&quot;password&quot; /> <br/> mot de passe encore une fois <input id=&quot;repassword&quot; type=&quot;password&quot;> <br/> <input type=&quot;button&quot; value=&quot;send&quot; onclick=&quot;validateForm();&quot;/> </form>
Javascript debugging Firebug – extension for Firefox Allows debugging of scripts Step by step execution Adding breakpoints Watch expressions Visualize the DOM tree
Javascript debugging example

C5 Javascript

  • 1.
    Client-side Scripting LanguagesIntroduction to Javascript
  • 2.
    Plan du courseJavascript – Pourquoi?, Ou?, Qu-est ce que c’est? Comment ajouter Javascript au HTML La syntaxe du Javascript Document Object Model Exemples
  • 3.
    Javascript – Pourquoi?,Ou?, Qu-est ce que c’est? Au début – simple texte + images + liens Des pages “live” ont été nécessaires sur le web Netscape a invente “LiveScript” en 1995 LiveScript a change le nom plus tard en Javascript Javascript – fonctionne sur des navigateurs, permet de l'accès dynamique à la page html Le langage a été interprété dans un façon différent de navigateurs différents
  • 4.
    Include Javascript intoHTML Script inclus dans la page html <script type=”text/javascript”> //code script </script> Script inclus dans un fichier extérieur <script src=”fisier_surse.js”></script>
  • 5.
    Quand est lecode exécuté Si le tag “script” est inclus dans le tag “head” Le script est exécuté lorsque la page est chargée - avant de rendre Si le script est inclus dans le corps page  Le script est exécuté lorsque le balisage est
  • 6.
    Syntaxe du JavascriptSimilaire avec C & Java Les variables n’ont pas du type Les variables sont déclaré en utilisant le mot “var” var x=5, y=7; Les fonctions sont déclaré en utilisant le mot “function” function sum(x,y) { var rez=x+y; return rez;} Les fonctions sont appelées comme en C/Java var suma=sum(2,5);
  • 7.
    Les objets duJavascript Les objets ont des methodes (fonctions) Proprietes Exemple var student={nom: &quot;ion&quot;, an:2, notes:{mate:9, pc:8}}; alert(student.nom +&quot;<br>&quot; ); alert(student.an +&quot;<br>&quot;);
  • 8.
    References pour lesobjets du Javascript Math http://www.w3schools.com/jsref/jsref_obj_math.asp String http://www.w3schools.com/jsref/jsref_obj_string.asp Array http://www.w3schools.com/jsref/jsref_obj_array.asp Date http://www.w3schools.com/jsref/jsref_obj_date.asp
  • 9.
    Examples <script type=&quot;text/javascript&quot;>function printValue() //declare a function { var x=Math.random()*10; //compute the value of x as a random value between 0 and 10 alert(x); //display an alert containing the value of x var y=&quot;a random text&quot;; //create a variable of type string alert(y.length); //display an alert containing the length of y //!!! length is a property and not a method alert(y.substr(0,5)); //compute and display as an alert the substring of y between the first and the 5 th character alert(x+&quot; &quot;+y.length+&quot; &quot;+y.substr(5,y.length)); //display as an alert the string formed by x, length of y and the substring formed from the 5 th character of y until the last one } </script>
  • 10.
    Javascript exemple -analyse “ +” est utilise pour aider les strings “ alert” est utilise pour afficher d’information pendant le développement. Il ne doit pas etre utilise en applications Les objets peuvent avoir des méthodes comme y.substr(0,5) et propriétés comme y.length
  • 11.
    Evénements Les élémentsdu HTML peuvent détecter quand l’utilisateur a des interactions avec eux Exemples d’interactions Mouse over (mouse out) Click Key pressed Blur change Nous pouvons écrire du code Javascript pour traiter les interactions
  • 12.
    Events examples <scripttype=“text/javascript”> function youClicked(element) {element.innerHTML=&quot;you clicked this element&quot;;} function youMousedOver() {alert(&quot;mouse over detected&quot;); } </script> <h1 onclick=&quot;alert('youclicked');youClicked( this );&quot; onmouseover=&quot;youMousedOver()&quot;> Introduction dans la programmation web</h1>
  • 13.
    Evénements Qu’est quec’est “this” Html element User interacts event1 event2 Event1 a une fonction javascript La fonction javascript doit savoir quel élément a modifier “ this” est la référence a l’objet qui doit être modifie
  • 14.
    DOM DOM=Document ObjectModel DOM = une representation des elements de la page HTML
  • 15.
    DOM The DOMtree contains nodes which can be Html elements Text The tree elements can be accessed By traversing the tree (See Data structures course) By accessing them directly by name (getElementsByTagName) By accessing them directly by id (getElementById) Addressing them directly (as in an array) The root of the DOM tree is the document
  • 16.
    Methods and propertiesdocument.write(“text”) Adds the “text” to the given page If the page is finished loading it rewrites it Example <script type=&quot;text/javascript&quot;> function printValue() { var x=Math.random()*10; alert(x); var y=&quot;a random text&quot;; alert(y.length); alert(y.substr(0,5)); alert(x+&quot; &quot;+y.length+&quot;!!!&quot;+y.substr(5,y.length)); document.write(x+&quot; &quot;+y.length+&quot;!!!&quot;+y.substr(5,y.length)); } </script>
  • 17.
    DOM Methods andproperties getElementsByTagName Returns an array of elements with a given name The we need to know the position of the element we need to modify inside the array function modifySecondH1() { var headersArray=document.getElementsByTagName(&quot;h1&quot;); //retrieves all the elements whose names are h1 //elements’ numbering in the array starts at 0 headersArray[1].innerHTML=Math.random()*5; }
  • 18.
    DOM Methods andproperties document.getElementById The most used method to access an element of a html page We have to be careful to set ids for the elements function modifyFirstH1() { //retrieve the element with the id h1id1 var h1Element=document.getElementById(&quot;h1id1&quot;); //set the HTML value for the document h1Element.innerHTML=&quot;new title&quot;; }
  • 19.
    DOM objects methodsand properties Direct access to the element Predefined collections Forms Links Images document.forms[0].username.value – accesses the first form in the document and sets the value property for the username input
  • 20.
    Example – usingjavascript to validate forms When a form is submitted we need to validate it first on the client-side The form should be validated before submitting The event should be added to the submit button For example we want to check if 2 passwords have the same value and if the username is longer than 4 characters
  • 21.
    Validate forms withJavascript – example (I) function validateForm(){ var usernameElement=document.getElementById(&quot;username&quot;); var passwordElement=document.getElementById(&quot;password&quot;); var rePasswordElement=document.getElementById(&quot;repassword&quot;); if(passwordElement.value!=rePasswordElement.value || passwordElement.value.length==0) {alert(&quot;please make sure the password is entered the same twice&quot;);return;} if (usernameElement.value.length<4) {alert(&quot;please make sure the username is longer than 4 letters&quot;);return; } document.forms[0].submit(); }
  • 22.
    Example of formvalidation with Javascript (II) <form action=&quot;script.php&quot; method=&quot;POST&quot;> nom d'utilisateur<input type=&quot;text&quot; id=&quot;username&quot; /><br/> mot de passe<input type=&quot;password&quot; id=&quot;password&quot; /> <br/> mot de passe encore une fois <input id=&quot;repassword&quot; type=&quot;password&quot;> <br/> <input type=&quot;button&quot; value=&quot;send&quot; onclick=&quot;validateForm();&quot;/> </form>
  • 23.
    Javascript debugging Firebug– extension for Firefox Allows debugging of scripts Step by step execution Adding breakpoints Watch expressions Visualize the DOM tree
  • 24.